using UnityEngine;
using Unity.VisualScripting;
using LS.Procedure;
using LS.Scene;

namespace LS.VisualScripting
{
    [UnitShortTitle("Scene Entry")]
    [UnitCategory("Events/LS")]
    public sealed class SceneEntry: GlobalEventUnit<(GameProcedureBase, SceneReference)>
    {
        public const string HookName = nameof(SceneEntry);
        protected override string hookName => HookName;

        [DoNotSerialize]
        public ValueOutput Procedure { get; set; }
        
        [DoNotSerialize]
        public ValueOutput SceneReference { get; set; }

        protected override void Definition()
        {
            base.Definition();
            Procedure =  ValueOutput<GameProcedureBase>(nameof(Procedure));
            SceneReference =  ValueOutput<SceneReference>(nameof(SceneReference));
        }

        protected override void AssignArguments(Flow flow, (GameProcedureBase, SceneReference) args)
        {
            base.AssignArguments(flow, args);
            flow.SetValue(Procedure, args.Item1);
            flow.SetValue(SceneReference, args.Item2);
        }

        public override void StartListening(GraphStack stack)
        {
            base.StartListening(stack);
            var scene = stack.gameObject.GetComponentInParent<SceneReference>();
            if(scene != null)
                scene.OnSceneEntry += SceneLeaveHandler;
        }

        public override void StopListening(GraphStack stack)
        {
            var scene = stack.gameObject.GetComponentInParent<SceneReference>();
            if(scene != null)
                scene.OnSceneEntry -= SceneLeaveHandler;
            base.StopListening(stack);
        }

        private void SceneLeaveHandler(GameProcedureBase procedure, SceneReference sceneReference)
        {
            EventBus.Trigger(HookName,(procedure, sceneReference));
        }
    }
}